package my.net.server;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import my.net.bean.Message;
import my.net.server.service.PushServer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHandler extends SimpleChannelUpstreamHandler {
	private static final Logger logger = LoggerFactory
			.getLogger(ServerHandler.class);

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		System.out.println("channelConnected");
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) {

		PushServer.channelDisconnected(ctx,e);

		System.out.println("channelDisconnected");
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws UnsupportedEncodingException {
		String json = ((ChannelBuffer) e.getMessage()).toString(Charset
				.forName("UTF-8"));
		Message msg = Message.build(json);
		System.out.println(msg);
		PushServer.process(msg, ctx, e);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		logger.error("error", e.getCause());
		
		PushServer.exceptionCaught(e);
		
	}
}
